// 认证策略过滤器
// @Author Heroic Yang

package filters

import (
	"regexp"
	//"strings"
	"encoding/json"
	"dhfshop/utils/response"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/context"
	jwt "github.com/dgrijalva/jwt-go"
)

var (
	authHeaderSchemeRe = regexp.MustCompile("^Bearer$")
)

func authenticationFilter(ctx *context.Context) {
	httpMethod := ctx.Input.Method()
	if httpMethod == "OPTIONS" {
	    return
	}
    authorizeToken := ctx.Input.Query("token")     //获取form方法
	if len(authorizeToken) < 5 {
		authorizeToken = ctx.Input.Header("Authorization")
	}
	if authorizeToken == "" {
	    //beego.Debug("authenticationFilter authorizeToken is null,url is:",ctx.Input.URL())
		ctx.Output.SetStatus(401)
	    outPut := response.Reponse(1, nil, "token为空")
		b, _ := json.Marshal(outPut)
		ctx.Output.Header("Access-Control-Allow-Origin", "*")
	    ctx.Output.JSON(string(b), false, false)
		return 
	}
	tokenSecret := beego.AppConfig.String("AuthTokenSecret")
	token, err := jwt.Parse(authorizeToken, func(token *jwt.Token) (interface{}, error) {
		return []byte(tokenSecret), nil
	})
	//claims := token.Claims.(jwt.MapClaims)
	switch err.(type) {
	    case nil:
		    if !token.Valid {
			    ctx.Output.SetStatus(401)
	            outPut := response.Reponse(1, nil, "token无效")
		        b, _ := json.Marshal(outPut)
		        ctx.Output.Header("Access-Control-Allow-Origin", "*")
	            ctx.Output.JSON(string(b), false, false)
			    return
		    }
			claims := token.Claims.(jwt.MapClaims)
		    curUserId := int(claims["CurrentUser"].(map[string]interface{})["Id"].(float64))
			curCompanyId := int(claims["CurrentUser"].(map[string]interface{})["CompanyId"].(float64))
		    curRoleId := int(claims["CurrentUser"].(map[string]interface{})["Role"].(float64))
			ctx.Input.SetData("curUserId", curUserId)
			ctx.Input.SetData("curCompanyId", curCompanyId)
			ctx.Input.SetData("curRoleId", curRoleId)
			if curRoleId == 1 {
			    curAppId := claims["CurrentUser"].(map[string]interface{})["AppId"].(string)
			    ctx.Input.SetData("curAppId", curAppId)
			}
			if curRoleId == 2 {
			    if _, ok := claims["CurrentUser"].(map[string]interface{})["SubRoleId"]; ok {
				    curSubRoleId := int(claims["CurrentUser"].(map[string]interface{})["SubRoleId"].(float64))
			        ctx.Input.SetData("curSubRoleId", curSubRoleId)
				}
				//
				if _, ok := claims["CurrentUser"].(map[string]interface{})["DhfxId"]; ok {
					curDhfxId := claims["CurrentUser"].(map[string]interface{})["DhfxId"].(string)
			        ctx.Input.SetData("curDhfxId", curDhfxId)
				}
				//
				if _, ok := claims["CurrentUser"].(map[string]interface{})["IsDealer"]; ok {
					curIsDealer := int(claims["CurrentUser"].(map[string]interface{})["IsDealer"].(float64))
			        ctx.Input.SetData("curIsDealer", curIsDealer)
				}
			}
	    case *jwt.ValidationError:
		    vErr := err.(*jwt.ValidationError)
		    switch vErr.Errors {
		        case jwt.ValidationErrorExpired:
				    ctx.Output.SetStatus(401)
	                outPut := response.Reponse(1, nil, "token过期,请重新登录")
		            b, _ := json.Marshal(outPut)
		            ctx.Output.Header("Access-Control-Allow-Origin", "*")
	                ctx.Output.JSON(string(b), false, false)
			        return
		        default:
			        ctx.Output.SetStatus(401)
	                outPut := response.Reponse(1, nil, "请先登录")
		            b, _ := json.Marshal(outPut)
		            ctx.Output.Header("Access-Control-Allow-Origin", "*")
	                ctx.Output.JSON(string(b), false, false)
			        return
		    }
	    default:
		    ctx.Output.SetStatus(401)
	        outPut := response.Reponse(1, nil, "请先登录")
		    b, _ := json.Marshal(outPut)
		    ctx.Output.Header("Access-Control-Allow-Origin", "*")
	        ctx.Output.JSON(string(b), false, false)
		    return
	}
}
